package com.jic.order.config.aop;

import com.jic.order.utils.JsonUtil;
import java.util.Arrays;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @author wj
 * @date: 2020年02月14日
 */
@Aspect
@Component
@Slf4j
public class VisitLogIntercept {

	ThreadLocal<Long> startTime = new ThreadLocal<Long>();

	//申明一个切点 里面是 execution表达式
	@Pointcut("execution(public * com.jic.order.controller.*..*.*(..))")
	private void controllerAspect() {
	}

	//请求method前打印内容
	@Before(value = "controllerAspect()")
	public void methodBefore(JoinPoint joinPoint) {
		startTime.set(System.currentTimeMillis());
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = requestAttributes.getRequest();

		//打印请求内容
		log.info("jic-order===============请求内容===============jic-order");
		log.info("请求地址:{}", request.getRequestURL().toString());
		log.info("请求方式:{}", request.getMethod());
		log.info("请求类方法:{}", joinPoint.getSignature());
		log.info("请求类方法参数:{}", Arrays.toString(joinPoint.getArgs()));
		log.info("jic-order===============请求内容===============jic-order");
	}

	//在方法执行完结后打印返回内容
	@AfterReturning(returning = "o", pointcut = "controllerAspect()")
	public void methodAfterReturning(Object o) {
		log.info("jic-order--------------返回内容----------------jic-order");
		log.info("Response内容:" + JsonUtil.toJson(o));
		log.info("jic-order--------------返回内容----------------jic-order");
		log.info("请求消耗时间：{}ms", (System.currentTimeMillis() - startTime.get()));
	}

}
